<!DOCTYPE html>
<html lang=zh>
<head>
  <meta charset="utf-8">
  
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
  <meta name="renderer" content="webkit">
  <meta http-equiv="Cache-Control" content="no-transform" />
  <meta http-equiv="Cache-Control" content="no-siteapp" />
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <meta name="format-detection" content="telephone=no,email=no,adress=no">
  <!-- Color theme for statusbar -->
  <meta name="theme-color" content="#000000" />
  <!-- 强制页面在当前窗口以独立页面显示,防止别人在框架里调用页面 -->
  <meta http-equiv="window-target" content="_top" />
  <!-- 谷歌收录 -->
  <meta name="google-site-verification" content="-5hl8eC4wfapGZhZouwMVUcKG0iaynijVRJbqVlzXm4" />
  
  
  <title>Windows命令行中正确显示颜色 | 鴻塵</title>
  <meta name="description" content="摘要：win10的cmd对颜色的显示不太友好，在捯饬的过程中差点把电脑搞崩。">
<meta property="og:type" content="article">
<meta property="og:title" content="Windows命令行中正确显示颜色">
<meta property="og:url" content="https://hwame.top/20210618/ansi-color-in-windows-cmd.html">
<meta property="og:site_name" content="鴻塵">
<meta property="og:description" content="摘要：win10的cmd对颜色的显示不太友好，在捯饬的过程中差点把电脑搞崩。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/hwame/pics@main/miscellanea/20210620颜色显示异常.png">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/hwame/pics@main/miscellanea/20210620颜色显示正常.png">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/hwame/pics@main/miscellanea/20210627ansicon命令.png">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/hwame/pics@main/miscellanea/20210627修改注册表.png">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/hwame/pics@main/miscellanea/20210627内存爆满.png">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/hwame/pics@main/miscellanea/20210627命令行窗口X.png">
<meta property="article:published_time" content="2021-06-18T12:03:20.000Z">
<meta property="article:modified_time" content="2021-06-27T10:33:59.000Z">
<meta property="article:author" content="鴻塵">
<meta property="article:tag" content="miscellanea">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://cdn.jsdelivr.net/gh/hwame/pics@main/miscellanea/20210620颜色显示异常.png">
  <!-- Canonical links -->
  <link rel="canonical" href="https://hwame.top/20210618/ansi-color-in-windows-cmd.html">
  
    <link rel="alternate" href="true" title="鴻塵" type="application/atom+xml">
  
  
    <link rel="icon" href="/favicon.png" type="image/x-icon">
  
  
<link rel="stylesheet" href="/css/style.css">

  
    <link href="//cdn.jsdelivr.net/npm/katex@0.9.0/dist/katex.min.css" rel="stylesheet">
  
  
  
    <link href="//cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css" rel="stylesheet">
  
  
<meta name="generator" content="Hexo 5.4.2"></head>


<script src="https://cdn.jsdelivr.net/gh/bobcn/hexo_resize_image.js@master/hexo_resize_image.js"></script>
<body class="main-center theme-purple" itemscope itemtype="http://schema.org/WebPage">
  <header class="header" itemscope itemtype="http://schema.org/WPHeader">
  <div class="slimContent">
    <div class="navbar-header">
      
      
      <div class="profile-block text-center">
        <a id="avatar" href="https://hwame.top" target="_blank">
          <img class="img-circle img-rotate" src="https://cdn.jsdelivr.net/gh/hwame/pics@main/avatar.jpg" width="200" height="200">
        </a>
        <h2 id="name" class="hidden-xs hidden-sm">鴻塵</h2>
        <h3 id="title" class="hidden-xs hidden-sm hidden-md">Pythoner, Data Analyst</h3>
        <small id="location" class="text-muted hidden-xs hidden-sm"><i class="icon icon-map-marker"></i> 湖北-武汉</small>
      </div>
      
      <div class="search" id="search-form-wrap">

    <form class="search-form sidebar-form">
        <div class="input-group">
            <input type="text" class="search-form-input form-control" placeholder="搜索" />
            <span class="input-group-btn">
                <button type="submit" class="search-form-submit btn btn-flat" onclick="return false;"><i class="icon icon-search"></i></button>
            </span>
        </div>
    </form>
    <div class="ins-search">
  <div class="ins-search-mask"></div>
  <div class="ins-search-container">
    <div class="ins-input-wrapper">
      <input type="text" class="ins-search-input" placeholder="想要查找什么..." x-webkit-speech />
      <button type="button" class="close ins-close ins-selectable" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
    </div>
    <div class="ins-section-wrapper">
      <div class="ins-section-container"></div>
    </div>
  </div>
</div>


</div>
      <button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target="#main-navbar" aria-controls="main-navbar" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
    </div>
    <nav id="main-navbar" class="collapse navbar-collapse" itemscope itemtype="http://schema.org/SiteNavigationElement" role="navigation">
      <ul class="nav navbar-nav main-nav menu-highlight">
        
        
        <li class="menu-item menu-item-home">
          <a href="/.">
            
            <i class="icon icon-home-fill"></i>
            
            <span class="menu-title">首页</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-archives">
          <a href="/archives">
            
            <i class="icon icon-archives-fill"></i>
            
            <span class="menu-title">归档</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-categories">
          <a href="/categories">
            
            <i class="icon icon-folder-open"></i>
            
            <span class="menu-title">分类</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-tags">
          <a href="/tags">
            
            <i class="icon icon-tags"></i>
            
            <span class="menu-title">标签</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-repository">
          <a href="/repository">
            
            <i class="icon icon-project"></i>
            
            <span class="menu-title">资源</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-gallery">
          <a href="/gallery">
            
            <i class="icon icon-delicious"></i>
            
            <span class="menu-title">相册</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-links">
          <a href="/links">
            
            <i class="icon icon-friendship"></i>
            
            <span class="menu-title">友链</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-about">
          <a href="/about">
            
            <i class="icon icon-cup-fill"></i>
            
            <span class="menu-title">关于</span>
          </a>
        </li>
        
      </ul>
      
	
    <ul class="social-links">
    	
        <li><a href="https://github.com/hwame" target="_blank" title="Github" data-toggle=tooltip data-placement=top><i class="icon icon-github"></i></a></li>
        
        <li><a href="https://weibo.com/hwamei" target="_blank" title="Weibo" data-toggle=tooltip data-placement=top><i class="icon icon-weibo"></i></a></li>
        
        <li><a href="https://www.zhihu.com/people/hwame" target="_blank" title="Zhihu" data-toggle=tooltip data-placement=top><i class="icon icon-zhihu"></i></a></li>
        
        <li><a href="https://segmentfault.com/u/hwame" target="_blank" title="Segmentfault" data-toggle=tooltip data-placement=top><i class="icon icon-segmentfault"></i></a></li>
        
        <li><a href="https://gitee.com/hwame" target="_blank" title="Gitee" data-toggle=tooltip data-placement=top><i class="icon icon-gitee"></i></a></li>
        
        <li><a href="/atom.xml" target="_blank" title="Rss" data-toggle=tooltip data-placement=top><i class="icon icon-rss"></i></a></li>
        
    </ul>

    </nav>
  </div>
</header>

  
    <aside class="sidebar" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    
      <div class="widget">
    <h3 class="widget-title"><i style="color:#9400D3" class="icon icon-stackexchange"></i>公告</h3>
    <div class="widget-body">
        <div id="board">
            <div class="content">
                <p>欢迎来到鴻塵的博客!<br>鴻塵的<u><a target="_blank" rel="noopener" href="https://weibo.com/hwamei" style="color:#E541E5;">微博</a></u>主页，鴻塵的<u><a target="_blank" rel="noopener" href="https://github.com/hwame" style="color:#E541E5;">Github</a></u>主页，如果我可以忘记的<u><a target="_blank" rel="noopener" href="https://www.zhihu.com/people/hwame" style="color:#E541E5;">知乎</a></u>主页。</p>
            </div>
        </div>
    </div>
</div>

    
      
  <div class="widget">
    <h3 class="widget-title"><i style="color:#9400D3" class="icon icon-tags"></i>标签云</h3>
    <div class="widget-body tagcloud">
      <a href="/tags/CentOS/" style="font-size: 13px; color: #fff">CentOS</a> <a href="/tags/Go/" style="font-size: 13.2px; color: #fff">Go</a> <a href="/tags/Hexo/" style="font-size: 13.8px; color: #fff">Hexo</a> <a href="/tags/Linux/" style="font-size: 14px; color: #fff">Linux</a> <a href="/tags/Linux%E9%83%A8%E7%BD%B2/" style="font-size: 13px; color: #fff">Linux部署</a> <a href="/tags/MongoDB/" style="font-size: 13.4px; color: #fff">MongoDB</a> <a href="/tags/Spark/" style="font-size: 13px; color: #fff">Spark</a> <a href="/tags/matplotlib/" style="font-size: 13.2px; color: #fff">matplotlib</a> <a href="/tags/miscellanea/" style="font-size: 13.6px; color: #fff">miscellanea</a> <a href="/tags/python/" style="font-size: 14px; color: #fff">python</a> <a href="/tags/shell/" style="font-size: 13.6px; color: #fff">shell</a> <a href="/tags/%E5%A4%A7%E6%95%B0%E6%8D%AE/" style="font-size: 13px; color: #fff">大数据</a> <a href="/tags/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E7%AE%97%E6%B3%95/" style="font-size: 13px; color: #fff">数据结构与算法</a> <a href="/tags/%E7%88%AC%E8%99%AB/" style="font-size: 13px; color: #fff">爬虫</a>
    </div>
  </div>

<script type="text/javascript">
    var everytag=document.getElementsByClassName("widget-body tagcloud")[0].children;
    for (var i = everytag.length - 1; i >= 0; i--) {
    	var r=Math.floor(Math.random()*255);
        var g=Math.floor(Math.random()*255);
        var b=Math.floor(Math.random()*255);
        everytag[i].style.background = "rgb("+r+","+g+","+b+")";
    }
</script>
    
      
  <div class="widget">
    <h3 class="widget-title"><i style="color:#9400D3" class="icon icon-folder-open"></i>分类</h3>
    <div class="widget-body">
      <ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/categories/Go/">Go</a><span class="category-list-count">2</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Hexo/">Hexo</a><span class="category-list-count">5</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/Linux/">Linux</a><span class="category-list-count">8</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/MongoDB/">MongoDB</a><span class="category-list-count">3</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/miscellanea/">miscellanea</a><span class="category-list-count">4</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/python/">python</a><span class="category-list-count">7</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E4%B8%8E%E7%AE%97%E6%B3%95/">数据结构与算法</a><span class="category-list-count">1</span></li></ul>
    </div>
  </div>


    
      
  <div class="widget">
    <h3 class="widget-title"><i style="color:#9400D3" class="icon icon-archives-fill"></i>归档</h3>
    <div class="widget-body">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2022/">2022</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/">2021</a><span class="archive-list-count">9</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/">2020</a><span class="archive-list-count">17</span></li></ul>
    </div>
  </div>


    
      
  <div class="widget">
    <h3 class="widget-title"><i style="color:#9400D3" class="icon icon-shu-fill"></i>最新文章</h3>
    <div class="widget-body">
      <ul class="recent-post-list list-unstyled ">
        
          <li>
            
            <div class="item-thumb">
              <a href="/20220327/channel-and-goroutine-in-go.html" class="thumb">
    
    
        <span style="background-image:url(https://cdn.jsdelivr.net/gh/hwame/pics@main/post-pics/icon-golang.jpeg)" alt="Go语言中的通道" class="thumb-image"></span>
    
</a>

            </div>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/categories/Go/">Go</a>
              </p>
              <p class="item-title">
                <a href="/20220327/channel-and-goroutine-in-go.html" class="title">Go语言中的通道</a>
              </p>
              <p class="item-date">
                <time datetime="2022-03-27T11:06:16.000Z" itemprop="datePublished">2022-03-27</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-thumb">
              <a href="/20220323/when-to-use-pointer-in-go.html" class="thumb">
    
    
        <span style="background-image:url(https://cdn.jsdelivr.net/gh/hwame/pics@main/post-pics/icon-golang.jpeg)" alt="Go语言什么时候使用指针" class="thumb-image"></span>
    
</a>

            </div>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/categories/Go/">Go</a>
              </p>
              <p class="item-title">
                <a href="/20220323/when-to-use-pointer-in-go.html" class="title">Go语言什么时候使用指针</a>
              </p>
              <p class="item-date">
                <time datetime="2022-03-23T12:49:57.000Z" itemprop="datePublished">2022-03-23</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-thumb">
              <a href="/20220228/awesome-images-in-markdown.html" class="thumb">
    
    
        <span style="background-image:url(https://cdn.jsdelivr.net/gh/hwame/pics@main/avatar.jpg)" alt="Markdown中图片的高级用法" class="thumb-image"></span>
    
</a>

            </div>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/categories/miscellanea/">miscellanea</a>
              </p>
              <p class="item-title">
                <a href="/20220228/awesome-images-in-markdown.html" class="title">Markdown中图片的高级用法</a>
              </p>
              <p class="item-date">
                <time datetime="2022-02-28T15:27:50.000Z" itemprop="datePublished">2022-02-28</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-thumb">
              <a href="/20220116/shell-regular-expression.html" class="thumb">
    
    
        <span style="background-image:url(https://cdn.jsdelivr.net/gh/hwame/pics@main/post-pics/linux-icon.png)" alt="Shell正则表达式" class="thumb-image"></span>
    
</a>

            </div>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/categories/Linux/">Linux</a>
              </p>
              <p class="item-title">
                <a href="/20220116/shell-regular-expression.html" class="title">Shell正则表达式</a>
              </p>
              <p class="item-date">
                <time datetime="2022-01-16T14:13:05.000Z" itemprop="datePublished">2022-01-16</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-thumb">
              <a href="/20211009/install-linux-on-android-phone.html" class="thumb">
    
    
        <span style="background-image:url(https://cdn.jsdelivr.net/gh/hwame/pics@main/avatar.jpg)" alt="如何在安卓手机上安装Linux发行版" class="thumb-image"></span>
    
</a>

            </div>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/categories/miscellanea/">miscellanea</a>
              </p>
              <p class="item-title">
                <a href="/20211009/install-linux-on-android-phone.html" class="title">如何在安卓手机上安装Linux发行版</a>
              </p>
              <p class="item-date">
                <time datetime="2021-10-09T15:16:37.000Z" itemprop="datePublished">2021-10-09</time>
              </p>
            </div>
          </li>
          
      </ul>
    </div>
  </div>
  

    
  </div>
</aside>

  
  
<aside class="sidebar sidebar-toc collapse" id="collapseToc" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    <nav id="toc" class="article-toc">
      <h3 class="toc-title">文章目录</h3>
      <ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#1-%E8%83%8C%E6%99%AF"><span class="toc-number">1.</span> <span class="toc-text">1.背景</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-%E8%A7%A3%E5%86%B3%E6%96%B9%E6%A1%88"><span class="toc-number">2.</span> <span class="toc-text">2.解决方案</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#2-1-colorama"><span class="toc-number">2.1.</span> <span class="toc-text">2.1.colorama</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-2-ANSICON"><span class="toc-number">2.2.</span> <span class="toc-text">2.2.ANSICON</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-%E9%87%87%E5%9D%91%E4%B9%8B%E8%B7%AF"><span class="toc-number">3.</span> <span class="toc-text">3.采坑之路</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#3-1-%E9%97%AE%E9%A2%98%E4%BA%A7%E7%94%9F"><span class="toc-number">3.1.</span> <span class="toc-text">3.1.问题产生</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-2-%E8%89%B0%E9%9A%BE%E8%A7%A3%E5%86%B3"><span class="toc-number">3.2.</span> <span class="toc-text">3.2.艰难解决</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4-%E9%99%84%E5%BD%95"><span class="toc-number">4.</span> <span class="toc-text">4.附录</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#4-1-ANSI%E9%A2%9C%E8%89%B2%E5%BA%8F%E5%88%97%E6%A0%BC%E5%BC%8F"><span class="toc-number">4.1.</span> <span class="toc-text">4.1.ANSI颜色序列格式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4-2-%E8%AE%BE%E7%BD%AE%E9%A2%9C%E8%89%B2"><span class="toc-number">4.2.</span> <span class="toc-text">4.2.设置颜色</span></a></li></ol></li></ol>
    </nav>
  </div>
</aside>

<main class="main" role="main">
  <div class="content">
  <article id="post-ansi-color-in-windows-cmd" class="article article-type-post" itemscope itemtype="http://schema.org/BlogPosting">
    
    <div class="article-header">
      
        
  
    <h1 class="article-title" itemprop="name">
      Windows命令行中正确显示颜色
    </h1>
  

      
      <div class="article-meta">
        <span class="article-date">
    <i class="icon icon-calendar"></i>
	<a href="/20210618/ansi-color-in-windows-cmd.html" class="article-date">
	  发布于 <time datetime="2021-06-18T12:03:20.000Z" itemprop="datePublished">2021-06-18</time>
	</a>
</span>
<span class="article-date">
    <i class="icon icon-calendar-check"></i>
	<a href="/20210618/ansi-color-in-windows-cmd.html" class="article-date">
	  更新于 <time datetime="2021-06-27T10:33:59.000Z" itemprop="dateUpdated">2021-06-27</time>
	</a>
</span>
        
  <span class="article-category">
    <i class="icon icon-folder"></i>
    <a class="article-category-link" href="/categories/miscellanea/">miscellanea</a>
  </span>

        
  <span class="article-tag">
    <i class="icon icon-tags"></i>
	<a class="article-tag-link-link" href="/tags/miscellanea/" rel="tag">miscellanea</a>
  </span>


        

	<span class="article-read hidden-xs">
    	<i class="icon icon-eye-fill" aria-hidden="true"></i>
    	<span id="/20210618/ansi-color-in-windows-cmd.html" class="leancloud_visitors"  data-flag-title="Windows命令行中正确显示颜色">
			<span class="leancloud-visitors-count">0</span>
		</span>
    </span>

        <span class="post-comment"><i class="icon icon-comment"></i> <a href="/20210618/ansi-color-in-windows-cmd.html#comments" class="article-comment-link">评论</a></span>
        
	
		<span class="post-wordcount hidden-xs" itemprop="wordCount">字数统计: 3.7k(字)</span>
	
	
		<span class="post-readcount hidden-xs" itemprop="timeRequired">阅读时长: 13(分)</span>
	

      </div>
      <div style="background-color:#D7BDE2;border:1px solid #D7BDE2;border-radius:10px;padding:5px">
          <b>温馨提示</b>：点击页面下方<i style="color:red" class="icon icon-anchor"></i>以展开或折叠目录
      </div>
    </div>
    <div class="article-entry marked-body" itemprop="articleBody">
      
        <p>摘要：win10的cmd对颜色的显示不太友好，在捯饬的过程中差点把电脑搞崩。<span id="more"></span></p>
<blockquote>
<p><font size=5><b>文章说明</b></font><br><strong>文章作者：</strong><a href="https://hwame.top">鴻塵</a><br><strong>参考资料：</strong></p>
<ul>
<li><a target="_blank" rel="noopener" href="https://blog.csdn.net/qq_15158911/article/details/88943571">解决CMD命令行窗口不显示颜色问题python</a></li>
<li><a target="_blank" rel="noopener" href="https://blog.csdn.net/qq_23452385/article/details/109271221">cmd命令提示符文本颜色输出</a></li>
<li><a target="_blank" rel="noopener" href="https://github.com/adoxa/ansicon">Github ANSICON</a></li>
<li><a target="_blank" rel="noopener" href="https://blog.csdn.net/Chameleons1/article/details/107338482">CMD窗口无法显示带颜色文字输出</a></li>
<li><a target="_blank" rel="noopener" href="https://blog.csdn.net/agzhchren/article/details/78940058">特殊命令之REG命令</a></li>
<li><a target="_blank" rel="noopener" href="https://blog.51cto.com/me2xp/1437542">转义序列Escape Sequences及Linux echo命令多种颜色显示</a></li>
<li><a target="_blank" rel="noopener" href="https://www.cnblogs.com/crabxx/p/4046498.html">Linux终端和win32控制台文本颜色输出</a></li>
<li><a target="_blank" rel="noopener" href="https://my.oschina.net/dingdayu/blog/1537064">控制台输出颜色控制（Console 模式下的颜色显示）</a></li>
<li><a target="_blank" rel="noopener" href="https://www.kancloud.cn/skyerisme/tech_knowledge/1778337">命令行里输出带颜色的字体</a></li>
<li><a target="_blank" rel="noopener" href="https://my.oschina.net/SamXIAO/blog/2959478">Windows cmd(DOS)命令窗口中echo命令ANSI转义显示彩色字或背景</a></li>
</ul>
<p><strong>文章链接：</strong><a href="https://hwame.top/20210618/ansi-color-in-windows-cmd.html">Windows命令行中正确显示颜色</a></p>
</blockquote>
<h2 id="1-背景"><a href="#1-背景" class="headerlink" title="1.背景"></a>1.背景</h2><blockquote>
<p>为了搞好这个问题，差点把电脑给搞崩了，在这里特意记录下来，算是留给自己的一个教训。</p>
</blockquote>
<p>临近毕业，这两天什么事情都没有，就等着参加毕业典礼然后跑路。就想着写点东西吧，hexo部署的时候无法正常显示颜色。如图（注意最后一行）：<br><img src="https://cdn.jsdelivr.net/gh/hwame/pics@main/miscellanea/20210620颜色显示异常.png" alt="颜色显示异常"><br><img src="https://cdn.jsdelivr.net/gh/hwame/pics@main/miscellanea/20210620颜色显示正常.png" alt="颜色显示正常"></p>
<p>其实呢，这个问题早就出现了，见<a href="https://hwame.top/20200520/hello-hexo-setup-deploy.html#5-5-%E9%83%A8%E7%BD%B2Hexo">Hexo博客搭建(1)——建站及部署之部署Hexo</a>，只不过一直没管它，现在闲下来了就想拯救一下处女座强迫症。</p>
<p>不仅如此，cmd中只能识别<code>^[[35m 文字 ^[[0m</code>而不能识别<code>\33[35m 文字 \33[0m</code>，也就是说无法正确转义<code>\033</code>。</p>
<p>需要注意的是，<code>^[</code>是一个字符，且只能在命令行下通过组合键<code>Ctrl + [</code>输入（还有其他方式输入，见后文）。</p>
<p>鉴于以上问题，在经过较长时间的折腾后，找到了一个可用的方法：<a target="_blank" rel="noopener" href="https://github.com/adoxa/ansicon">ANSICON</a>。</p>
<h2 id="2-解决方案"><a href="#2-解决方案" class="headerlink" title="2.解决方案"></a>2.解决方案</h2><h3 id="2-1-colorama"><a href="#2-1-colorama" class="headerlink" title="2.1.colorama"></a>2.1.<code>colorama</code></h3><p>在Python中显示颜色主要参考「<a target="_blank" rel="noopener" href="https://blog.csdn.net/qq_15158911/article/details/88943571">解决CMD命令行窗口不显示颜色问题python</a>」，用到的库为<code>colorama</code>，代码如下：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> colorama <span class="keyword">import</span> init </span><br><span class="line">init(autoreset=<span class="literal">True</span>)</span><br><span class="line"> </span><br><span class="line"><span class="built_in">print</span>(<span class="string">&quot;\033[35m 紫色 \033[0m&quot;</span>) <span class="comment">#紫色</span></span><br></pre></td></tr></table></figure></p>
<p>上述方法通过颜色代码实现颜色的显示，也可以使用<code>Fore</code>设置颜色：<br><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> colorama <span class="keyword">import</span> init, Fore</span><br><span class="line">init(autoreset=<span class="literal">True</span>)</span><br><span class="line"></span><br><span class="line"><span class="built_in">print</span>(Fore.YELLOW + <span class="string">&quot;黄色&quot;</span>)</span><br><span class="line"><span class="built_in">print</span>(<span class="string">&quot;普通文字&quot;</span>) </span><br><span class="line"><span class="built_in">print</span>(Fore.MAGENTA + <span class="string">&quot;洋红色&quot;</span>)</span><br></pre></td></tr></table></figure><br><code>colorama</code>方法只适用于python程序在终端上打印彩色文字，并不能解决其他程序的输出。</p>
<h3 id="2-2-ANSICON"><a href="#2-2-ANSICON" class="headerlink" title="2.2.ANSICON"></a>2.2.<code>ANSICON</code></h3><p>鉴于上述问题，在查找了海量资料后，参考「<a target="_blank" rel="noopener" href="https://blog.csdn.net/qq_23452385/article/details/109271221">cmd命令提示符文本颜色输出</a>」，最终找到了<a target="_blank" rel="noopener" href="https://github.com/adoxa/ansicon">ANSICON</a>。<br>ANSICON基本上可以完美解决遇到的关于cmd颜色的所有问题，这是它的自我介绍：</p>
<blockquote>
<p>ANSICON provides ANSI escape sequences for Windows console programs. It provides much the same functionality as <code>ANSI.SYS</code> does for MS-DOS.</p>
</blockquote>
<p>在64位Windows上，ANSICON包含了主程序<code>ansicon.exe</code>和扩展<code>ANSI64.dll</code>，在cmd中运行该程序即可<strong>开启一个子shell</strong>，在子shell中即可<a target="_blank" rel="noopener" href="https://cdn.jsdelivr.net/gh/hwame/pics@main/miscellanea/20210620颜色显示正常.png">正常显示</a>颜色，不会出现<a target="_blank" rel="noopener" href="https://cdn.jsdelivr.net/gh/hwame/pics@main/miscellanea/20210620颜色显示异常.png">图一</a>的问题。</p>
<p>ANSICON帮助信息如下：<br><figure class="highlight stata"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">ANSICON <span class="keyword">by</span> Jason Hood &lt;jadoxa@yahoo.com.au&gt;.</span><br><span class="line"><span class="keyword">Version</span> 1.89 (29 April, 2019).  Freeware.</span><br><span class="line">http:<span class="comment">//ansicon.adoxa.vze.com/</span></span><br><span class="line"></span><br><span class="line">Process ANSI escape sequences <span class="keyword">in</span> Windows console programs.</span><br><span class="line"></span><br><span class="line">ansicon [-lLEVEL] [-i] [-I] [-<span class="keyword">u</span>] [-<span class="keyword">U</span>] [-<span class="keyword">m</span>[ATTR]] [-p[<span class="keyword">u</span>]]</span><br><span class="line">        [-<span class="keyword">e</span>|<span class="keyword">E</span> STRING | -t|T [<span class="keyword">FILE</span>...] | <span class="keyword">PROGRAM</span> [<span class="keyword">ARGS</span>]]</span><br><span class="line"></span><br><span class="line">  -<span class="keyword">l</span>            <span class="keyword">set</span> the logging level (1=process, 2=module, 3=function,</span><br><span class="line">                 +4=output, +8=<span class="keyword">append</span>, +16=imports, +32=files) <span class="keyword">for</span> <span class="keyword">PROGRAM</span></span><br><span class="line">  -i            install - add ANSICON to CMD&#x27;s AutoRun entry (also implies -p)</span><br><span class="line">  -<span class="keyword">u</span>            uninstall - remove ANSICON from the AutoRun entry</span><br><span class="line">  -I -<span class="keyword">U</span>         <span class="keyword">use</span> <span class="keyword">local</span> machine instead of current user</span><br><span class="line">  -<span class="keyword">m</span>            <span class="keyword">use</span> grey <span class="keyword">on</span> black (<span class="string">&quot;monochrome&quot;</span>) or ATTR <span class="keyword">as</span> default color</span><br><span class="line">  -p            hook into the parent process</span><br><span class="line">  -pu           unhook from the parent process</span><br><span class="line">  -<span class="keyword">e</span>            echo STRING</span><br><span class="line">  -<span class="keyword">E</span>            echo STRING, don&#x27;t <span class="keyword">append</span> newline</span><br><span class="line">  -t            <span class="keyword">display</span> files (<span class="string">&quot;-&quot;</span> <span class="keyword">for</span> stdin), combined <span class="keyword">as</span> a single stream</span><br><span class="line">  -T            <span class="keyword">display</span> files, name first, blank <span class="keyword">line</span> before and after</span><br><span class="line">  <span class="keyword">PROGRAM</span>       <span class="keyword">run</span> the specified <span class="keyword">program</span></span><br><span class="line">  nothing       <span class="keyword">run</span> a new command processor, or <span class="keyword">display</span> stdin <span class="keyword">if</span> redirected</span><br><span class="line"></span><br><span class="line">ATTR is <span class="keyword">one</span> or <span class="keyword">two</span> hexadecimal digits; please <span class="keyword">use</span> <span class="string">&quot;COLOR /?&quot;</span> <span class="keyword">for</span> details.</span><br><span class="line">It may start with &#x27;-&#x27; to reverse foreground and background (but not <span class="keyword">for</span> -p).</span><br></pre></td></tr></table></figure></p>
<p>由上可知，直接运行该程序将不带任何参数，开启一个新的命令行进程，这也是后来悲催的直接原因。现在看来，貌似只需要加上<code>-i</code>选项将其添加到cmd的<code>AutoRun</code>即可。</p>
<h2 id="3-采坑之路"><a href="#3-采坑之路" class="headerlink" title="3.采坑之路"></a>3.采坑之路</h2><h3 id="3-1-问题产生"><a href="#3-1-问题产生" class="headerlink" title="3.1.问题产生"></a>3.1.问题产生</h3><p>到目前为止，好像一切正常，文章开始说的「差点把电脑搞崩」又是怎么回事呢？</p>
<p>因为担心会出现其他问题，所以并没有安装ANSICON，开启子shell<strong>好像</strong>也没有什么问题，无非就是每次都要手动输入命令<code>/path/to/ansicon.exe</code>。这也不是什么问题，只要把<code>ansicon.exe</code>文件路径加入到环境变量中即可。<br>为了省事我直接把<code>ansicon.exe</code>和<code>ANSI64.dll</code>复制到<code>C:/Windows/System32/</code>目录下，这样一来在任何命令行下都可以直接运行<code>ansicon</code>命令了。</p>
<p>当需要正常显示颜色时，输入<code>ansicon</code>即可，如图所示：<br><img src="https://cdn.jsdelivr.net/gh/hwame/pics@main/miscellanea/20210627ansicon命令.png" alt="ansicon命令开启子shell"><br>上图中，直接打印颜色将显示乱码，在ansicon的子shell中则可以正常显示，输入<code>exit</code>才可退出shell。此时再打印颜色仍会乱码，因为只有在ansicon的shell中才可以正常显示。</p>
<p>在查资料的时候，偶然看到了一篇文章：<a target="_blank" rel="noopener" href="https://blog.csdn.net/Chameleons1/article/details/107338482">CMD窗口无法显示带颜色文字输出</a>。文章中提到，利用注册表的<code>AutoRun</code>字符串值可以实现在打开CMD窗口时自动执行命令。于是，我就设想修改注册表，在每次打开CMD的时候让他自动执行<code>ansicon</code>命令，那么就不需要手动输入了。</p>
<p>说干就干，<code>Win + R</code>打开运行，输入<code>regedit</code>打开注册表编辑器，定位到<code>计算机\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Command Processor</code>下，新建字符串值<code>AutoRun</code>，双击该值，在数值数据中填写<code>ansicon</code>，一气呵成。<br><img src="https://cdn.jsdelivr.net/gh/hwame/pics@main/miscellanea/20210627修改注册表.png" alt="修改注册表"></p>
<p>此时我已经迫不及待地要测试了，然而，当我打开cmd的时候，窗口中却疯狂打印<code>Microsoft Windows [版本 10.0.18363.1556](c) 2019 Microsoft Corporation。保留所有权利。</code>，此时我已经感觉不妙。好在它只开了一个窗口（注意，这是一个伏笔……），我不得不一直按<code>Ctrl + C</code>让它停下来，甚至直接叉掉这个窗口。</p>
<p>我又查了半天，一直都以为是注册表修改方式不对，又不知道在哪里看到了<code>cmd /k xxx</code>这样的一个命令，就是这个命令让我的电脑直接崩溃。该命令会打开一个新窗口来执行<code>xxx</code>命令。于是抱着试一试的心态我把上面注册表的数值数据改成了<code>cmd /k ansicon</code>，当我打开CMD窗口的一瞬间，电脑内存急剧增加，无限开启新窗口并执行<code>ansicon</code>命令。</p>
<p>自此走上了修电脑的艰难之路。</p>
<h3 id="3-2-艰难解决"><a href="#3-2-艰难解决" class="headerlink" title="3.2.艰难解决"></a>3.2.艰难解决</h3><p>由于电脑内存卡爆，无法进行任何操作，就算想删除注册表值也没办法，因为鼠标键盘根本动不了。无奈之下，准备重启电脑，跟它抢速度，在内存爆满之前把注册表改回来。事实证明我还是太天真了，电脑一开机他就开始了，根本不给时间你去做其他操作，如图：<br><img src="https://cdn.jsdelivr.net/gh/hwame/pics@main/miscellanea/20210627内存爆满.png" alt="内存爆满"></p>
<p>到这里已经没有任何办法了，系统还原也不行，因为我很早就删除了系统还原点（只为节省那么一丢丢内存…），现在只能重装系统了，甚至连U盘启动盘都做好了。重装系统倒是无所谓，但是电脑里有很多重要的文件、配置、安装的软件等。我真的不想重装系统，但是没办法啊！</p>
<p>上图是准备重装系统之前拍的照，为的是留一个桌面布局，可以看到右侧命令行窗口边缘厚厚的一层黑边，都不知道开了多少个窗口了。</p>
<p>从U盘重装系统还要设置一下BIOS，开启UEFI什么的。然而哪有那么顺利，就在我失败了无数次一心想要操作系统的时候，他却提示各种错误，要么是某个地方设置不对、要么是某个选项没有开启。在反复的重启和设置中，突然发现了一个修复的选项。在这种连系统都不让我重装的情况下，无疑给了我一丝希望。</p>
<p>然而，新的问题又出现了，所有的修复选项都试过了还是没用，这让我整个人都不好了，一度濒临崩溃。</p>
<p>世事总是这样，在你最绝望的时候才会显现一丝曙光。</p>
<p>在某一个修复选项中，可以打开命令行窗口，目测盘符<code>X</code>应该是U盘吧，<code>Source</code>目录就是启动盘的位置。如图所示：<br><img src="https://cdn.jsdelivr.net/gh/hwame/pics@main/miscellanea/20210627命令行窗口X.png" alt="命令行窗口X"></p>
<p>但是一个命令行能干什么呢？这里的命令行是有管理员权限的，最直接的想法就是在这里删除注册表值，然后重启就完美了。<br>搜了一下，发现还真有操作注册表的命令<code>REG</code>，还有对应的<code>QUREY</code>、<code>ADD</code>、<code>DELETE</code>等选项，此处参考了<a target="_blank" rel="noopener" href="https://blog.csdn.net/agzhchren/article/details/78940058">特殊命令之REG命令</a>。这令我大喜过望，感觉胜利就在眼前。然而，当我查询<code>HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Command Processor</code>下的值时，却没有<code>AutoRun</code>这一项（如上图），只有如下几项：<br><figure class="highlight apache"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">CompletionChar</span>      REG_DWORD    <span class="number">0</span>x9</span><br><span class="line"><span class="attribute">DefaultColor</span>        REG_DWORD    <span class="number">0</span>x0</span><br><span class="line"><span class="attribute">EnableExtensions</span>    REG_DWORD    <span class="number">0</span>x1</span><br><span class="line"><span class="attribute">PathCompletionChar</span>  REG_DWORD    <span class="number">0</span>x9</span><br></pre></td></tr></table></figure><br>通过对比<a href="#3-1-%E9%97%AE%E9%A2%98%E4%BA%A7%E7%94%9F">3.1节《问题产生》</a>的图二和上图，唯独少了<code>AutoRun</code>这一项。这另外百思不得其解的同时，也是十分郁闷。我测试过<code>REG ADD</code>和<code>REG DELETE</code>，好像都成功了，为何这里就查询不到呢？看来这个方法又行不通了。</p>
<p>就在我一筹莫展的时候，突然灵机一动，产生问题的根本原因在于无限启动新窗口从而运行<code>ansicon</code>命令，那我可以人为破坏掉他的运行环境啊。<br>于是我在命令行里试着删除文件<code>C:\Windows\System32\ANSI64.dll</code>，结果成功了。</p>
<p>赶紧重启电脑，尽管仍然会无限开启新窗口，但果然没那么卡了，因为<code>ansicon</code>命令无法正常运行。于是可以打开注册表编辑器，删除掉罪魁祸首<code>AutoRun</code>，再重启电脑就恢复正常了。</p>
<p>至此，历经千辛万苦，电脑总算是修好了，可算是不需要重装系统了。</p>
<h2 id="4-附录"><a href="#4-附录" class="headerlink" title="4.附录"></a>4.附录</h2><h3 id="4-1-ANSI颜色序列格式"><a href="#4-1-ANSI颜色序列格式" class="headerlink" title="4.1.ANSI颜色序列格式"></a>4.1.ANSI颜色序列格式</h3><blockquote>
<p>本段来自<a target="_blank" rel="noopener" href="https://blog.51cto.com/me2xp/1437542">转义序列Escape Sequences及Linux echo命令多种颜色显示</a>。<br>在计算机界，ANSI<strong>转义编码（escape code）</strong>或者<strong>转义序列（escape sequences）</strong>是带内信号（元数据和控制信号，译者注）控制视频文字终端的格式、颜色、其他输出选项的一种方法。<br>为了编码这些格式信息，它把某种字节序列嵌入到文本中，该序列必须特别的解释，且不应该作为字符的本义。<br>尽管硬件字符终端在21世纪已经变得很愈来愈少见，这种标准依然具有实用价值，是因为大多数终端仿真器至少还能解释在输出文本中的一些ANSI转义序列。<br>但微软的win32控制台组件就是一个明显的例外。</p>
</blockquote>
<p>上文中的「<code>\033[35m</code>」和「<code>\033[0m</code>」就是ANSI转义序列（ANSI escape code/sequence），转义序列使用ESC控制字符开始，ESC键位于键盘左上角，其对应的ASCII码为<code>\033（八进制）</code>、<code>\27（十进制）</code>和<code>\0x1b（十六进制）</code>。</p>
<p>通用的控制文本颜色的转义序列格式为<code>CSI n1[;n2[;...]] m</code>，其中<code>CSI</code>全称为「控制序列引导器（Control Sequence Introducer/Initiator）」，即上述<code>\033</code>、<code>\x1b</code>和<code>\e</code>等；<code>n1</code>、<code>n2</code>等表示SGR参数，多个SGR参数可以组合使用，见下表。</p>
<p>通常，我们只需要用到表中部分属性，更详细的属性值可参考<a target="_blank" rel="noopener" href="https://www.kancloud.cn/skyerisme/tech_knowledge/1778337">命令行里输出带颜色的字体</a>。</p>
<p>一般格式：<code>CSI[显示方式;前景色;背景色m 文字 CSI[0m</code>。</p>
<blockquote>
<p><strong>注：</strong>经测试，在Linux下<code>\033</code>、<code>\x1b</code>和<code>\e</code>可用，<code>\33</code>、<code>\0x1b</code>和<code>\27</code>不可用。<br><strong>注：</strong>在Windows下只有<code>\033</code>、<code>\33</code>、<code>\x1b</code>、<code>^[</code>可用（不一定准确），<code>\e</code>不可用。</p>
</blockquote>
<div class="table-container">
<table>
<thead>
<tr>
<th style="text-align:center">编码</th>
<th style="text-align:center">说明</th>
<th style="text-align:center">备注</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center"><code>0</code></td>
<td style="text-align:center">关闭所有格式，还原为初始状态</td>
<td style="text-align:center">终端默认设置</td>
</tr>
<tr>
<td style="text-align:center"><code>1</code></td>
<td style="text-align:center">粗体/高亮显示</td>
<td style="text-align:center">无</td>
</tr>
<tr>
<td style="text-align:center"><code>2</code></td>
<td style="text-align:center">模糊/弱化</td>
<td style="text-align:center">不是所有的终端仿真器都支持，只有少数仿真器支持</td>
</tr>
<tr>
<td style="text-align:center"><code>3</code></td>
<td style="text-align:center">斜体</td>
<td style="text-align:center">不是所有的终端仿真器都支持，只有少数仿真器支持</td>
</tr>
<tr>
<td style="text-align:center"><code>4</code></td>
<td style="text-align:center">下划线（单线）</td>
<td style="text-align:center">无</td>
</tr>
<tr>
<td style="text-align:center"><code>5</code></td>
<td style="text-align:center">闪烁（慢）</td>
<td style="text-align:center">无</td>
</tr>
<tr>
<td style="text-align:center"><code>6</code></td>
<td style="text-align:center">闪烁（快）</td>
<td style="text-align:center">不是所有的终端仿真器都支持，只有少数仿真器支持</td>
</tr>
<tr>
<td style="text-align:center"><code>7</code></td>
<td style="text-align:center">交换背景色与前景色（反显）</td>
<td style="text-align:center">无</td>
</tr>
<tr>
<td style="text-align:center"><code>8</code></td>
<td style="text-align:center">隐藏（伸手不见五指，啥也看不见）</td>
<td style="text-align:center">不是所有的终端仿真器都支持，只有少数仿真器支持</td>
</tr>
<tr>
<td style="text-align:center"><code>22</code></td>
<td style="text-align:center">设置一般密度</td>
<td style="text-align:center">无</td>
</tr>
<tr>
<td style="text-align:center"><code>24</code></td>
<td style="text-align:center">关闭下划线</td>
<td style="text-align:center">无</td>
</tr>
<tr>
<td style="text-align:center"><code>25</code></td>
<td style="text-align:center">关闭闪烁</td>
<td style="text-align:center">无</td>
</tr>
<tr>
<td style="text-align:center"><code>27</code></td>
<td style="text-align:center">关闭反向图像，即关闭<code>7</code></td>
<td style="text-align:center">无</td>
</tr>
<tr>
<td style="text-align:center"><code>30-37</code></td>
<td style="text-align:center">前景色，即<code>30+x</code>，<code>x</code>表示不同的颜色（参见下面的「颜色表」）</td>
<td style="text-align:center">无</td>
</tr>
<tr>
<td style="text-align:center"><code>38</code></td>
<td style="text-align:center">在缺省的前景颜色上设置下划线</td>
<td style="text-align:center">无</td>
</tr>
<tr>
<td style="text-align:center"><code>39</code></td>
<td style="text-align:center">在缺省的前景颜色上关闭下划线</td>
<td style="text-align:center">无</td>
</tr>
<tr>
<td style="text-align:center"><code>40-47</code></td>
<td style="text-align:center">背景色，即<code>40+x</code>，<code>x</code>表示不同的颜色（参见下面的「颜色表」）</td>
<td style="text-align:center">无</td>
</tr>
<tr>
<td style="text-align:center"><code>49</code></td>
<td style="text-align:center">设置缺省黑色背景</td>
<td style="text-align:center">无</td>
</tr>
</tbody>
</table>
</div>
<div class="table-container">
<table>
<thead>
<tr>
<th style="text-align:center">颜色值<code>x</code></th>
<th style="text-align:center">前景色编码</th>
<th style="text-align:center">背景色编码</th>
<th style="text-align:center">颜色</th>
<th style="text-align:center">效果</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center"><code>0</code></td>
<td style="text-align:center"><code>30</code></td>
<td style="text-align:center"><code>40</code></td>
<td style="text-align:center">黑色</td>
<td style="text-align:center"><font color=#000000>黑色</font></td>
</tr>
<tr>
<td style="text-align:center"><code>1</code></td>
<td style="text-align:center"><code>31</code></td>
<td style="text-align:center"><code>41</code></td>
<td style="text-align:center">红色</td>
<td style="text-align:center"><font color=#FF0000>红色</font></td>
</tr>
<tr>
<td style="text-align:center"><code>2</code></td>
<td style="text-align:center"><code>32</code></td>
<td style="text-align:center"><code>42</code></td>
<td style="text-align:center">绿色</td>
<td style="text-align:center"><font color=#008000>绿色</font></td>
</tr>
<tr>
<td style="text-align:center"><code>3</code></td>
<td style="text-align:center"><code>33</code></td>
<td style="text-align:center"><code>43</code></td>
<td style="text-align:center">黄色</td>
<td style="text-align:center"><font color=#FFFF00>黄色</font></td>
</tr>
<tr>
<td style="text-align:center"><code>4</code></td>
<td style="text-align:center"><code>34</code></td>
<td style="text-align:center"><code>44</code></td>
<td style="text-align:center">蓝色</td>
<td style="text-align:center"><font color=#0000FF>蓝色</font></td>
</tr>
<tr>
<td style="text-align:center"><code>5</code></td>
<td style="text-align:center"><code>35</code></td>
<td style="text-align:center"><code>45</code></td>
<td style="text-align:center">紫色</td>
<td style="text-align:center"><font color=#800080>紫色</font></td>
</tr>
<tr>
<td style="text-align:center"><code>6</code></td>
<td style="text-align:center"><code>36</code></td>
<td style="text-align:center"><code>46</code></td>
<td style="text-align:center">青色</td>
<td style="text-align:center"><font color=#00FFFF>青色</font></td>
</tr>
<tr>
<td style="text-align:center"><code>7</code></td>
<td style="text-align:center"><code>37</code></td>
<td style="text-align:center"><code>47</code></td>
<td style="text-align:center">白色</td>
<td style="text-align:center"><font color=#FFFFFF>白色</font></td>
</tr>
</tbody>
</table>
</div>
<h3 id="4-2-设置颜色"><a href="#4-2-设置颜色" class="headerlink" title="4.2.设置颜色"></a>4.2.设置颜色</h3><p>一般格式：<code>CSI</code> <code>[</code> <code>显示方式;</code> <code>前景色;</code> <code>背景色</code> <code>m</code> <code>文字部分</code> <code>CSI</code> <code>[</code> <code>0</code> <code>m</code>。</p>
<div class="table-container">
<table>
<thead>
<tr>
<th style="text-align:center"><code>CSI</code></th>
<th style="text-align:center">显示方式</th>
<th style="text-align:center">前景色</th>
<th style="text-align:center">背景色</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center"><code>\033</code> <code>\x1b</code> <code>\e</code><br><code>ESC（^[）</code></td>
<td style="text-align:center"><code>0-9</code>等</td>
<td style="text-align:center"><code>30-37</code></td>
<td style="text-align:center"><code>40-47</code></td>
</tr>
</tbody>
</table>
</div>
<p>需要说明的是，在同一处的CSI最好保持一致，「显示方式」、「前景色」和「背景色」的顺序不重要。</p>
<p>关于Windows下CMD中<code>ESC（^[）</code>的输入方式，参考<a target="_blank" rel="noopener" href="https://my.oschina.net/SamXIAO/blog/2959478">《Windows cmd(DOS)命令窗口中echo命令ANSI转义显示彩色字或背景》</a>：</p>
<blockquote>
<p>Windows下CMD中<code>^[</code>是ANSI的ESC一个字符（注意<code>^</code>和<code>[</code>是一个字符，就好比我们<code>Ctrl + C</code>时显示的<code>^C</code>一样），并不是我们看到的键盘上左上角那个ESC按键。其ASCII码值的十进制是<code>27</code>， 八进制是<code>33</code>（一般写为<code>\033</code>)，十六进制是<code>1b</code>（一般写为<code>\x1b</code>）。其输入方法有以下几种：</p>
<ul>
<li><strong>方法一</strong>（只能在CMD窗口中输入）：在CMD窗口中按<code>Ctrl + [</code>组合键即可，这种方法最简单。</li>
<li><strong>方法二</strong>（只能在CMD窗口中输入）：在CMD窗口中按<code>Alt + 2 + 7</code>组合键即可，注意必须是小键盘上的数字键<code>2</code>和<code>7</code>，先按住<code>Alt</code>不放再按<code>2</code>和<code>7</code>最后放开<code>Alt</code>。如果没有数字小键盘，则不能用这种方式。</li>
<li><strong>方法三</strong>（编辑器中先输入再替换）：略。垃圾软件不配。</li>
</ul>
</blockquote>

      
    </div>
    <div class="article-footer">
      <blockquote class="mt-2x">
  <ul class="post-copyright list-unstyled">
    <li class="post-copyright-license">
      <strong>文章作者： </strong><a href="https://hwame.top" style="color:#E541E5;"> 鴻塵</a>
    </li>
    
    <li class="post-copyright-link hidden-xs">
      <strong>本文链接：</strong>
      <a href="https://hwame.top/20210618/ansi-color-in-windows-cmd.html" title="Windows命令行中正确显示颜色" target="_blank" rel="external" style="color:#E541E5;">https://hwame.top/20210618/ansi-color-in-windows-cmd.html</a>
    </li>
    
    <li class="post-copyright-license">
      <strong>版权声明： </strong> 本博客所有文章除特别声明外，均采用《<a href="http://creativecommons.org/licenses/by/4.0/deed.zh" target="_blank" rel="external" style="color:#E541E5;"><u>CC BY 4.0 CN协议</u></a>》许可协议。转载请注明出处！
    </li>
  </ul>
</blockquote>


<div class="panel panel-default panel-badger">
  <div class="panel-body">
    <figure class="media">
      <div class="media-left">
        <a href="https://hwame.top" target="_blank" class="img-burn thumb-sm visible-lg">
          <img src="https://cdn.jsdelivr.net/gh/hwame/pics@main/avatar.jpg" class="img-rounded w-full" alt="">
        </a>
      </div>
      <div class="media-body">
        <h3 class="media-heading"><a href="https://hwame.top" target="_blank"><span class="text-dark">鴻塵</span><small class="ml-1x">Pythoner, Data Analyst</small></a></h3>
        <div>个人简介：处女座不适合做码农。</div>
      </div>
    </figure>
  </div>
</div>


    </div>
  </article>
  
    
  <section id="comments">
  	
      <div id="vcomments"></div>
    
  </section>


  
</div>

  <nav class="bar bar-footer clearfix" data-stick-bottom>
  <div class="bar-inner">
  
  <ul class="pager pull-left">
    
    <li class="prev">
      <a href="/20210629/python-virtual-environment.html" title="Python虚拟环境"><i class="icon icon-angle-left" aria-hidden="true"></i><span>&nbsp;&nbsp;上一篇</span></a>
    </li>
    
    
    <li class="next">
      <a href="/20210610/flatten-a-nested-list.html" title="如何将嵌套列表展开为一维"><span>下一篇&nbsp;&nbsp;</span><i class="icon icon-angle-right" aria-hidden="true"></i></a>
    </li>
    
    
    <li class="toggle-toc">
      <a class="toggle-btn collapsed" data-toggle="collapse" href="#collapseToc" aria-expanded="false" title="文章目录" role="button">
        <span style="color:#C71585">[&nbsp;</span><span style="color:#C71585">文章目录</span>
        <i class="text-collapsed icon icon-anchor"></i>
        <i class="text-in icon icon-close"></i>
        <span style="color:#C71585">]</span>
      </a>
    </li>
    
  </ul>
  
  
  
  <div class="bar-right">
    
    <div class="share-component" data-sites="weibo,qq,wechat,facebook,twitter" data-mobile-sites="weibo,wechat,qq,qzone"></div>
    
  </div>
  </div>
</nav>
  


</main>

  <script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<footer class="footer" itemscope itemtype="http://schema.org/WPFooter">
	
	
    <ul class="social-links">
    	
        <li><a href="https://github.com/hwame" target="_blank" title="Github" data-toggle=tooltip data-placement=top><i class="icon icon-github"></i></a></li>
        
        <li><a href="https://weibo.com/hwamei" target="_blank" title="Weibo" data-toggle=tooltip data-placement=top><i class="icon icon-weibo"></i></a></li>
        
        <li><a href="https://www.zhihu.com/people/hwame" target="_blank" title="Zhihu" data-toggle=tooltip data-placement=top><i class="icon icon-zhihu"></i></a></li>
        
        <li><a href="https://segmentfault.com/u/hwame" target="_blank" title="Segmentfault" data-toggle=tooltip data-placement=top><i class="icon icon-segmentfault"></i></a></li>
        
        <li><a href="https://gitee.com/hwame" target="_blank" title="Gitee" data-toggle=tooltip data-placement=top><i class="icon icon-gitee"></i></a></li>
        
        <li><a href="/atom.xml" target="_blank" title="Rss" data-toggle=tooltip data-placement=top><i class="icon icon-rss"></i></a></li>
        
    </ul>

    <div class="copyright">
    	
        &copy; 2025 鴻塵
        
        
        <div class="publishby" style="font-family:Courier">
            <span id="busuanzi_container_site_pv">
                <i class="icon icon-eye"></i><span id="busuanzi_value_site_pv" style="font-family:Courier"></span>&nbsp;
                <i class="icon icon-users"></i><span id="busuanzi_value_site_uv" style="font-family:Courier"></span>
            </span>
            <!--
            <br>✯<a target="_blank" rel="noopener" href="https://beian.miit.gov.cn/" style="color:#0FFFAA">鄂ICP备2020019329号</a>
            -->
            <br><i class="icon icon-clock" style="transform:rotate(90deg)"></i><span id="sitetime" style="font-family:Courier"></span>
        </div>
        
        <!--
        <div class="publishby">
        	Theme by <a href="https://github.com/cofess" target="_blank"> cofess </a>base on <a href="https://github.com/cofess/hexo-theme-pure" target="_blank">pure</a>.
        </div>
        -->
    </div>
    
</footer>
<script>
    function siteTime(){
        window.setTimeout("siteTime()", 1000);
        var seconds = 1000;
        var minutes = seconds * 60;
        var hours = minutes * 60;
        var days = hours * 24;
        var years = days * 365;
        var today = new Date();
        var todayYear = today.getFullYear();
        var todayMonth = today.getMonth()+1;
        var todayDate = today.getDate();
        var todayHour = today.getHours();
        var todayMinute = today.getMinutes();
        var todaySecond = today.getSeconds();
        /* Date.UTC() -- 返回date对象距世界标准时间(UTC)1970年1月1日午夜之间的毫秒数(时间戳)
        year - 作为date对象的年份，为4位年份值
        month - 0-11之间的整数，做为date对象的月份
        day - 1-31之间的整数，做为date对象的天数
        hours - 0(午夜24点)-23之间的整数，做为date对象的小时数
        minutes - 0-59之间的整数，做为date对象的分钟数
        seconds - 0-59之间的整数，做为date对象的秒数
        microseconds - 0-999之间的整数，做为date对象的毫秒数 */
        var t1 = Date.UTC(2020,05,19,21,20,52); //建站时间
        var t2 = Date.UTC(todayYear,todayMonth,todayDate,todayHour,todayMinute,todaySecond);
        var diff = t2-t1;
        var diffYears = Math.floor(diff/years);
        var diffDays = Math.floor((diff/days)-diffYears*365);
        var diffHours = Math.floor((diff-(diffYears*365+diffDays)*days)/hours);
        var diffMinutes = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours)/minutes);
        var diffSeconds = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours-diffMinutes*minutes)/seconds);
        // 将「数字」转「补零字符串」
        var y = diffYears.toString()
        var d = diffDays.toString().padStart(3, '0')
        var h = diffHours.toString().padStart(2, '0')
        var m = diffMinutes.toString().padStart(2, '0')
        var s = diffSeconds.toString().padStart(2, '0')
        document.getElementById("sitetime").innerHTML=y+":"+d+":"+h+":"+m+":"+s;
    }
    siteTime();
</script>
  <script src="//cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
<script>
window.jQuery || document.write('<script src="js/jquery.min.js"><\/script>')
</script>
<div id="go-top"></div>
<style type="text/css">
#go-top {
 width:40px;height:40px;
 background-color:#DDA0DD;
 position:relative;
 border-radius:20px;
 position:fixed;right:20px;bottom:50px;
 cursor:pointer;display:none;
}
#go-top:after {
 content:" ";
 position:absolute;left:14px;top:14px;
 border-top:2px solid #fff;border-right:2px solid #fff;
 width:12px;height:12px;
 transform:rotate(-45deg);
}
#go-top:hover {
 background-color:#8A2BE2;
}
</style>
<script>
$(function () {
  var top=$("#go-top");
  $(window).scroll(function () {
    ($(window).scrollTop() > 300) ? top.show(300) : top.hide(200);
    $("#go-top").click(function () {
      $('body,html').animate({scrollTop:0});
      return false();
    })
  });
});
</script>

<script src="/js/plugin.min.js"></script>


<script src="/js/application.js"></script>


    <script>
(function (window) {
    var INSIGHT_CONFIG = {
        TRANSLATION: {
            POSTS: '文章',
            PAGES: '页面',
            CATEGORIES: '分类',
            TAGS: '标签',
            UNTITLED: '(未命名)',
        },
        ROOT_URL: '/',
        CONTENT_URL: '/content.json',
    };
    window.INSIGHT_CONFIG = INSIGHT_CONFIG;
})(window);
</script>

<script src="/js/insight.js"></script>





   




   
    

  <script src='/waline.js'></script>
  <link rel="stylesheet" type="text/css" href="/waline.css" />
  
  <script type="text/javascript">
 
  
Waline.init({
      el: '#vcomments',
      serverURL: 'https://waline.hwame.top',
});
  </script>

     


<!-- 20201211添加判断 -->

   
  <script src="//cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js"></script>
  <script>
  //利用 FancyBox 实现点击图片放大
  $(document).ready(function() {
    $('article img').not('[hidden]').not('.panel-body img').each(function() {
      var $image = $(this);
      var imageCaption = $image.attr('alt');
      var $imageWrapLink = $image.parent('a');
      if ($imageWrapLink.length < 1) {
        var src = this.getAttribute('src');
        var idx = src.lastIndexOf('?');
        if (idx != -1) {
          src = src.substring(0, idx);
        }
        $imageWrapLink = $image.wrap('<a href="' + src + '"></a>').parent('a');
      }
      $imageWrapLink.attr('data-fancybox', 'images');
      if (imageCaption) {
        $imageWrapLink.attr('data-caption', imageCaption);
      }
    });
    $().fancybox({
      selector: '[data-fancybox="images"]',
      hash: false,
      loop: true,
    });
  });
  </script>







  
  <style>
    .copy-btn {
      display: inline-block;
      padding: 6px 12px;
      font-size: 13px;
      font-weight: 700;
      line-height: 20px;
      color: #333;
      white-space: nowrap;
      vertical-align: middle;
      cursor: pointer;
      background-color: #eee;
      background-image: linear-gradient(#fcfcfc, #eee);
      border: 1px solid #d5d5d5;
      border-radius: 3px;
      user-select: none;
      outline: 0;
    }

    .highlight-wrap .copy-btn {
      transition: opacity .3s ease-in-out;
      opacity: 0;
      padding: 2px 6px;
      position: absolute;
      right: 4px;
      top: 8px;
      z-index: 2;
    }

    .highlight-wrap:hover .copy-btn,
        .highlight-wrap .copy-btn:focus {
      opacity: 1
    }

    .highlight-wrap {
      position: relative;
    }
  </style>
  
  <script>
    addLoadEvent(()=>{
      $('.highlight').each(function (i, e) {
        var $wrap = $('<div>').addClass('highlight-wrap')
        $(e).after($wrap)
        $wrap.append($('<button>').addClass('copy-btn').append('一键复制').on('click', function (e) {
          var code = $(this).parent().find(".code")[0].innerText
          
          var ta = document.createElement('textarea')
          document.body.appendChild(ta)
          ta.style.position = 'absolute'
          ta.style.top = '0px'
          ta.style.left = '0px'
          ta.value = code
          ta.select()
          ta.focus()
          var result = document.execCommand('copy')
          document.body.removeChild(ta)
          
            if(result)$(this).text('复制成功')
            else $(this).text('复制失败')
          
          $(this).blur()
        })).on('mouseleave', function (e) {
          var $b = $(this).find('.copy-btn')
          setTimeout(function () {
            $b.text('一键复制')
          }, 300)
        }).append(e)
      })
    })
  </script>

<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
        tex2jax: {
            inlineMath: [ ["$","$"], ["\\(","\\)"] ],
            skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code'],
            processEscapes: true
        }
    });
    MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax();
        for (var i = 0; i < all.length; ++i)
            all[i].SourceElement().parentNode.className += ' has-jax';
    });
</script>
<script src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
</body>
</html>